package com.stud.admin.controller.file;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.stud.common.core.controller.BaseController;
import com.stud.common.core.domain.Result;
import com.stud.common.core.page.TableDataInfo;
import com.stud.common.dto.FileToMultipartFile;
import com.stud.common.enums.BusinessEnum;
import com.stud.common.exception.ServiceException;
import com.stud.common.utils.poi.ExcelUtil;
import com.stud.system.domain.FileLink;
import com.stud.system.factory.FileEngineBuilder;
import com.stud.system.properties.FileProperties;
import com.stud.system.service.FileEngine;
import com.stud.system.service.FileLinkService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 系统文件关联Controller
 *
 * @author Stud
 * @date 2022-10-08
 */
@Tag(name = "系统文件关联")
@RestController
@RequestMapping("/fileLink")
@Slf4j
@RequiredArgsConstructor
public class FileLinkController extends BaseController {

    private final FileLinkService fileLinkService;

    private final FileProperties fileProperties;

    @Operation(description = "如果是minio获取下载链接(180分钟有效)， 如果是本地url就是永久有效")
    @GetMapping("/getDownloadUrl")
    public Result<String> getDownloadUrl(String fileKey) {
        return Result.ok(fileLinkService.getDownloadUrl(fileKey));
    }

    @Operation(description = "获取文件存储目录")
    @GetMapping("/getFileFolder")
    public Result<String> getFileFolder() {
        return Result.ok(fileProperties.getFolder());
    }

    @Operation(description = "查询系统文件关联列表")
    @GetMapping("/list")
    public TableDataInfo<FileLink> list(FileLink fileLink) {
        startPage();
        Wrapper<FileLink> wrapper = Wrappers.lambdaQuery(fileLink);
        List<FileLink> list = fileLinkService.list(wrapper);
        return getDataTable(list);
    }

    @Operation(description = "导出系统文件关联列表")
    @PostMapping("/export")
    public void export(HttpServletResponse response, FileLink fileLink) {
        Wrapper<FileLink> wrapper = Wrappers.lambdaQuery(fileLink);
        List<FileLink> list = fileLinkService.list(wrapper);
        ExcelUtil<FileLink> util = new ExcelUtil<>(FileLink.class);
        util.exportExcel(response, list, "系统文件关联数据");
    }

    @Operation(description = "获取系统文件关联详细信息")
    @GetMapping(value = "/{id}")
    public Result<FileLink> getInfo(@PathVariable("id") Long id) {
        return Result.ok(fileLinkService.getById(id));
    }

    @Operation(description = "新增系统文件关联")
    @PostMapping
    public Result<Boolean> add(@Validated @RequestBody FileLink fileLink) {
        return Result.ok(fileLinkService.save(fileLink));
    }

    @Operation(description = "修改系统文件关联")
    @PutMapping
    public Result<Boolean> edit(@Validated @RequestBody FileLink fileLink) {
        return Result.ok(fileLinkService.update(fileLink));
    }

    @Operation(description = "删除文件关联(物理)")
    @PostMapping("/deletePhysical")
    public Result<Boolean> deletePhysical(@RequestParam("ids") Long[] ids) {
        return Result.ok(fileLinkService.deletePhysical(ids));
    }

    @Operation(description = "删除文件关联(逻辑)")
    @DeleteMapping("/deleteLogical")
    public Result<Boolean> removeBatchByIds(@RequestParam("ids") Long[] ids) {
        List<FileLink> list = fileLinkService.listByIds(Arrays.asList(ids));
        if (CollectionUtils.isEmpty(list)) {
            return Result.fail("数据异常");
        }
        for (FileLink fileLink : list) {
            fileLink.setDelFlag("1");
        }
        return Result.ok(fileLinkService.updateBatchById(list));
    }

    @Operation(description = "删除文件关联(物理删除,根据fileKey)")
    @DeleteMapping("/deletePhysicalByFileKey")
    public Result<Boolean> deletePhysicalByFileKey(@RequestParam("fileKeys") List<String> fileKeys) {
        LambdaQueryWrapper<FileLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(FileLink::getFileKey, fileKeys);
        List<FileLink> list = fileLinkService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return Result.fail("数据异常");
        }
        return Result.ok(this.fileLinkService.deletePhysical(list));
    }

    @Operation(description = "删除文件关联(逻辑删除,根据fileKey)")
    @DeleteMapping("/deleteLogicalByFileKey")
    public Result<Boolean> deleteLogicalByFileKey(@RequestParam("fileKey") String fileKey) {
        LambdaQueryWrapper<FileLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileLink::getFileKey, fileKey);
        FileLink fileLink = fileLinkService.getOne(queryWrapper);
        fileLink.setDelFlag("1");
        return Result.ok(fileLinkService.updateById(fileLink));
    }

    @Operation(description = "下载文件")
    @GetMapping("/download")
    public void download(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request) {
        try {
            FileLink fileLink = this.fileLinkService.getById(id);
            if (Objects.isNull(fileLink)) {
                throw new ServiceException("查询附件失败");
            }
            response.setContentType("application/x-download");
            response.setCharacterEncoding(request.getCharacterEncoding());
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileLink.getFileName(), Constants.UTF_8));
            FileEngine fileEngine = FileEngineBuilder.build();
            fileEngine.download(fileLink.getFileKey(), response.getOutputStream());
        } catch (IOException e) {
            throw new ServiceException("文件下载失败");
        }
    }

    @Operation(description = "通过路径下载文件")
    @GetMapping("/downloadByFileKey")
    public void downloadByFileKey(@RequestParam("fileKey") String fileKey, HttpServletResponse response, HttpServletRequest request) {
        try {
            FileLink fileLink = this.fileLinkService.getLinkByFileKey(fileKey);
            if (Objects.isNull(fileLink)) {
                throw new ServiceException("查询附件失败");
            }
            response.setContentType("application/x-download");
            response.setCharacterEncoding(request.getCharacterEncoding());
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileLink.getFileName(), Constants.UTF_8));
            FileEngine fileEngine = FileEngineBuilder.build();
            fileEngine.download(fileLink.getFileKey(), response.getOutputStream());
        } catch (IOException e) {
            throw new ServiceException("文件下载失败");
        }
    }

    @Operation(description = "查询关联文件列表")
    @GetMapping("/linkList")
    public TableDataInfo<FileLink> linkList(@RequestParam("businessEnum") BusinessEnum businessEnum, @RequestParam("businessId") Long businessId) {
        LambdaQueryWrapper<FileLink> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FileLink::getBusinessEnum, businessEnum);
        queryWrapper.eq(FileLink::getBusinessId, businessId);
        startPage();
        return getDataTable(fileLinkService.list(queryWrapper));
    }

    @Operation(description = "上传附件")
    @PostMapping("/upload")
    public Result<FileLink> upload(@RequestParam("businessEnum") BusinessEnum businessEnum, @RequestPart("file") MultipartFile file) {
        return Result.ok(fileLinkService.upload(businessEnum, file));
    }

    @Operation(description = "上传附件并关联业务")
    @PostMapping("/uploadLink")
    public Result<FileLink> uploadLink(@RequestParam("businessEnum") BusinessEnum businessEnum, @RequestParam("businessId") Long businessId, @RequestPart("file") MultipartFile file) {
        return Result.ok(fileLinkService.uploadLink(businessEnum, businessId, file));
    }

    @Operation(description = "上传附件并关联业务")
    @PostMapping("/uploadLinkLocal")
    public Result<FileLink> uploadLinkLocal(@RequestParam("businessEnum") BusinessEnum businessEnum, @RequestParam("businessId") Long businessId, @RequestParam("path") String path) {
        File file = new File(path);
        if (!file.exists()) {
            return Result.fail("文件不存在");
        }
        return uploadLink(businessEnum, businessId, new FileToMultipartFile(file));
    }

    @Operation(description = "上传附件并关联业务(批量)")
    @PostMapping("/uploadLinkBatch")
    public Result<List<FileLink>> uploadLinkBatch(@RequestParam("businessEnum") BusinessEnum businessEnum, @RequestParam("businessId") Long businessId, @RequestPart("file") MultipartFile[] file) {
        return Result.ok(fileLinkService.uploadLink(businessEnum, businessId, file));
    }

    @Operation(description = "根据业务ID获取附件列表")
    @PostMapping("/linkMap")
    public Result<Map<Long, List<FileLink>>> linkMap(@RequestParam("businessEnum") BusinessEnum businessEnum, @RequestParam("businessIds") List<Long> businessIds) {
        return Result.ok(fileLinkService.linkMap(businessEnum, businessIds));
    }

    @Operation(description = "根据业务ID获取附件ID列表")
    @PostMapping("/linkIdMap")
    public Result<Map<Long, List<Long>>> linkIdMap(@RequestParam("businessEnum") BusinessEnum businessEnum, @RequestParam("businessIds") List<Long> businessIds) {
        return Result.ok(fileLinkService.linkIdMap(businessEnum, businessIds));
    }

    @Operation(description = "附件上报")
    @PostMapping("/fileReport")
    public Result<?> fileReport(@RequestParam("fileName") String fileName, @RequestPart("file") MultipartFile file) {
        return Result.ok(this.fileLinkService.fileReport(fileName, file));
    }

    @Operation(description = "返回FileProperties")
    @GetMapping("/getFileProperties")
    public Result<FileProperties> getFileProperties() {
        return Result.ok(fileProperties);
    }
}
